package com.auroramanito.uaa.domain;

import com.auroramanito.uaa.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// 新增通过改变一个属性返回一个新对象的方法。
@With
//通过.builder().属性链式赋值
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EqualsAndHashCode
@Entity
@Table(name = "mooc_users")
public class User implements UserDetails, Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 80,unique = true,nullable = false)
    private String username;

    //不显示密码
    @JsonIgnore
    @Column(name="password_hash",length = 255,nullable = false)
    private String password;

    @Column(length = 255,unique = true,nullable = false)
    private String email;

    @NotNull
    @Pattern(regexp = Constants.PATTERN_MOBILE)
    @Column(length = 50)
    private String mobile;

    @Column(length = 50)
    private String name;

    @Column(nullable = false)
    private boolean enabled;

    @Column(name = "account_non_expired",nullable = false)
    private boolean accountNonExpired;

    @Column(name = "account_non_locked",nullable = false)
    private boolean accountNonLocked;

    @Column(name = "credentials_non_expired",nullable = false)
    private boolean credentialsNonExpired;

    /**
     * 是否启用两步验证
     * */
    @Builder.Default
    @Column(name = "using_mfa",nullable = false)
    private boolean usingMfa = false;

    /**
     * 两步验证的key
     * */
    @JsonIgnore
    @Column(name = "mfa_key",nullable = false)
    private String mfaKey;


    @JsonIgnore
    @ManyToMany
    @Fetch(FetchMode.JOIN)
    @JoinTable(name = "mooc_users_roles",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName="id")}
    )
    private Set<Role> roles = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        /**
         * flatMap  先扁平化，再f
         * 将角色 和 角色拥有的权限进行合并，设置为权限。
         * */
        return roles.stream().flatMap(
                role -> Stream.concat(
                        Stream.of(
                                new SimpleGrantedAuthority(role.getRoleName())
                        ),
                        role.getPermissions().stream()
                )
        ).collect(Collectors.toList());
    }
}
